<template>
  <div>
    <Card dis-hover :bordered="false">
      <Form class="ivu-mb-16">
        <Input
          v-width="260"
          clearable
          class="ivu-mr-8"
          placeholder="请输入患者姓名、手机号"
          v-model="formItem.keyword"
          @on-enter="keyWordSearch"
          @on-clear="clearKeyWord"
        />
        <!-- <DatePicker :editable="false"
                    :clearable="false"
                    v-model="formItem.dateMonth"
                    class="ivu-mr-8"
                    v-width="200"
                    type="month"
                    format="yyyy-MM"
                    @on-change="changeParams"
                /> -->
        <DatePicker
          type="daterange"
          v-model="formItem.dateMonth"
          class="ivu-mr-8"
          @on-change="changeParams"
          placeholder="请选择时间段"
          v-width="200"
          :clearable="false"
          :options="options1"
        />
        <!-- <Select
          v-width="118"
          class="ivu-mr-8"
          clearable
          placeholder="请选择渠道类型"
          v-model="formItem.source_channel_type"
          @on-change="changeParamsChannel"
        >
          <Option
            v-for="(item, index) in channel"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</Option
          >
        </Select> -->
        <TreeSelect
          class="ivu-mr-8"
          placeholder="渠道来源"
          v-model="formItem.source_channel_id"
          :data="channel_types"
          v-width="118"
          clearable
          filterable
          @on-change="changeParams"
        />
        <TreeSelect
          class="ivu-mr-8"
          placeholder="病种"
          v-model="formItem.diseases_id"
          :data="diseases_list"
          v-width="118"
          clearable
          filterable
          @on-change="changeParams"
        />
        <searchTree
          :multiple="true"
          :options="belongData"
          placeholder="归属人"
          :limit="3"
          :normalizer="normalizer"
          @input="valueChange"
          :limitText="limitText"
          noResultsText="无数据"
        />
        <!-- <Select
                    v-width="118"
                    class="ivu-mr-8"
                    clearable
                    filterable
                    placeholder="请选择归属人"
                    v-model="formItem.belong_member_id"
                    @on-change="changeParams"
                >
                    <OptionGroup
                        v-for="(items, index) in member_list"
                        :key="items.value"
                        :label="items.label"
                    >
                        <Option
                            v-for="item in items.children"
                            :value="item.value"
                            :key="item.value"
                        >{{ item.label }}</Option
                        >
                    </OptionGroup>
                </Select> -->
        <!-- <Checkbox
          class="ivu-ml-16"
          v-model="formItem.noConsumer"
          @on-change="changeParams"
          label="未消费"
          >未消费</Checkbox
        > -->
        <Checkbox
          class="ivu-ml-16"
          v-model="formItem.un_by"
          @on-change="changeParams"
          label="未匹配到诊"
          >未匹配到诊</Checkbox
        >
        <Button @click="exportData" class="ivu-mr-8 bt" type="primary">
          导出
        </Button>
        <Button
          @click="batchData"
          class=""
          :loading="batchLoading"
          type="primary"
        >
          批量同步
        </Button>
      </Form>
      <Table :columns="columns" :data="dataWithPage" :loading="loading">
        <template slot="basic" slot-scope="{ row }">
          <span>{{ row.user_name }}</span>
          <span>{{ row.gender_str }}</span>
          <span>{{ row.age }}</span>
        </template>
        <template slot="operation" slot-scope="{ row }">
          <a @click="synchronization(row)">同步</a>
        </template>
        <template slot="label" slot-scope="{ row }">
          <template
            v-if="
              row.by_revisiting_time === '' &&
                row.dt_tags.length === 0 &&
                row.by_tags.length === 0
            "
          >
            <span>/</span>
          </template>
          <template v-else>
            <Tag v-if="item !== ''" v-for="item in row.dt_tags" :key="item">{{
              item
            }}</Tag>
            <Tag v-if="item !== ''" v-for="item in row.by_tags" :key="item">{{
              item
            }}</Tag>
          </template>
        </template>
      </Table>
      <div class="ivu-mt ivu-text-center">
        <Page
          :total="total"
          :current.sync="formItem.page"
          show-elevator
          show-sizer
          show-total
          @on-change="changePage"
          @on-page-size-change="changeSize"
        />
      </div>
    </Card>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { mapState } from "vuex";
import {
  patientReportInfo,
  arriveReport,
  arriveReportExport,
  statisticspatientarrivereportmatchdata,
  consumeauthlist,
  arrivereportSync,
} from "@/api/TApi/index.js";
import searchTree from "@riophae/vue-treeselect";
export default {
  name: "analysisReport",
  components: { searchTree },
  data() {
    return {
      loading: false,
      batchLoading: false,
      current: 1,
      dataWithPage: [],
      belongData: [],
      belongValue: [],
      normalizer(node) {
        return {
          id: node.value,
          label: node.label,
          children: node.children,
        };
      },
      limitText: function(count) {
        return `+ ${count}`;
      },
      total: 0,
      formItem: {
        keyword: "",
        page: 1,
        pageSize: "10",
        times: "",
        dateMonth: ["", ""],
        // source_channel_type: "",
        source_channel_id: "",
        belong_member_id: "",
        diseases_id: "",
        // noConsumer: "",
        un_by: "",
      },
      timer: "",
      // channel: [],
      channel_types: [],
      member_list: [],
      diseases_list: [],
      source_channel_list: [],
      source_channel_market_list: [],
      columns: [],
      columnss: [
        {
          title: "基本信息",
          slot: "basic",
          width: 158,
          fixed: "left",
        },
        // {
        //     title: '门诊信息',
        //     key: 'baiyouBasic',
        //     width: 100,
        //     fixed: 'left'
        // },
        // {
        //     title: '年龄',
        //     key: 'age',
        //     width: 90
        // },
        {
          title: "人员",
          key: "belong_member",
          width: 100,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.belong_member === ""
                ? "/"
                : params.row.belong_member
            );
          },
        },
        // {
        //   title: "渠道类型",
        //   key: "source_channel_type",
        //   width: 100,
        //   render: (h, params) => {
        //     return h(
        //       "div",
        //       {},
        //       params.row.by_revisiting_time === "" &&
        //         params.row.source_channel_type === ""
        //         ? "/"
        //         : params.row.source_channel_type
        //     );
        //   },
        // },
        {
          title: "来源渠道",
          key: "channel_str",
          width: 150,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.channel_str === ""
                ? "/"
                : params.row.channel_str
            );
          },
        },
        {
          title: "搜索词",
          key: "search_word",
          width: 260,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.search_word === ""
                ? "/"
                : params.row.search_word
            );
          },
        },
        {
          title: "关键词",
          key: "keyword",
          width: 220,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" && params.row.keyword === ""
                ? "/"
                : params.row.keyword
            );
          },
        },
        {
          title: "标签",
          slot: "label",
          width: 200,
        },
        // {
        //     title: '电话后四位',
        //     key: 'phone',
        //     width: 118
        // },
        {
          title: "疾病类型",
          key: "diseases_type",
          width: 200,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.diseases_type === ""
                ? "/"
                : params.row.diseases_type
            );
          },
        },
        {
          title: "诊断类型",
          key: "diagnosis_type",
          width: 180,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.diagnosis_type === ""
                ? "/"
                : params.row.diagnosis_type
            );
          },
        },
        {
          title: "地区",
          key: "city_area",
          width: 90,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.city_area === ""
                ? "/"
                : params.row.city_area
            );
          },
        },
        {
          title: "诊疗号",
          key: "patient_card_id",
          width: 150,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.patient_card_id === ""
                ? "/"
                : params.row.patient_card_id
            );
          },
        },
        {
          title: "到诊日期",
          key: "dt_revisiting_time",
          width: 128,
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.by_revisiting_time === "" &&
                params.row.dt_revisiting_time === ""
                ? "/"
                : params.row.dt_revisiting_time
            );
          },
        },
        {
          title: "创建日期",
          key: "patient_created_at",
          width: 170,
        },
        // {
        //     title: '来院次数',
        //     key: 'frequency',
        //     width: 100
        // },
        // {
        //     title: "初诊消费",
        //     key: "first_consume",
        //     width: 100,
        // },
        // {
        //     title: '总消费',
        //     key: 'totalConsume',
        //     width: 100
        // }

        {
          title: "操作",
          slot: "operation",
          width: 90,
          fixed: "right",
        },
      ],
      section_id: "",
      member: [],
      options1: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  computed: {
    ...mapState("admin/user", ["info"]),
  },
  mounted() {
    this._patientReportInfo();
    this.consumeauthlist();
    this.formItem.dateMonth = [
      this.$Date(`${this.$Date().format("YYYY-MM")}-1`),
      this.$Date(),
    ];
    // this.columns = this.columnss;
    this.columns = JSON.parse(JSON.stringify(this.columnss));
    let Projectid = localStorage.getItem("currentProject");
    let Projectcity = JSON.parse(localStorage.getItem("project"));
    for (let item of Projectcity) {
      if (+Projectid === +item.project_id) {
        this.section_id = item.section_id;
      }
    }
    // if (+this.section_id === 2) {
    //     this.columns.push({
    //         title: '消费',
    //         key: 'first_consume',
    //         width: 100,
    //         render: (h, params) => {
    //             return h(
    //                 'div',
    //                 {},
    //                 params.row.by_revisiting_time === '' &&
    //                     params.row.kq_reality_money === '0.00'
    //                     ? '/'
    //                     : params.row.kq_reality_money
    //             );
    //         }
    //     });
    //     this.columns.push({
    //         title: '退费',
    //         key: 'kq_refund',
    //         width: 100,
    //         render: (h, params) => {
    //             return h(
    //                 'div',
    //                 {},
    //                 params.row.by_revisiting_time === '' &&
    //                     params.row.kq_refund === '0.00'
    //                     ? '/'
    //                     : params.row.kq_refund
    //             );
    //         }
    //     });
    // } else if (+this.info.is_super === 1 ||this.member.includes(+this.info.member_id)) {
    //     this.columns.push({
    //         title: '初诊消费',
    //         key: 'first_consume',
    //         width: 100,
    //         render: (h, params) => {
    //             return h(
    //                 'div',
    //                 {},
    //                 params.row.by_revisiting_time === '' &&
    //                     params.row.first_consume === '0.00'
    //                     ? '/'
    //                     : params.row.first_consume
    //             );
    //         }
    //     }, {
    //         title: '季度消费',
    //         key: 'quarter_consume',
    //         width: 100,
    //         render: (h, params) => {
    //             return h(
    //                 'div',
    //                 {},
    //                 params.row.by_revisiting_time === '' &&
    //                     params.row.quarter_consume === '0.00'
    //                     ? '/'
    //                     : params.row.quarter_consume
    //             );
    //         }
    //     }, {
    //         title: '年度消费',
    //         key: 'year_consume',
    //         width: 100,
    //         render: (h, params) => {
    //             return h(
    //                 'div',
    //                 {},
    //                 params.row.by_revisiting_time === '' &&
    //                     params.row.year_consume === '0.00'
    //                     ? '/'
    //                     : params.row.year_consume
    //             );
    //         }
    //     });
    // }
  },
  methods: {
    synchronization(row) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        let params = {
          patient_user_id: row.patient_user_id,
          patient_card_id: row.patient_card_id,
        };
        statisticspatientarrivereportmatchdata(params).then((res) => {
          if (res.matching_num == 0) {
            this.$Modal.error({
              title: "温馨提示",
              content:
                "当前数据暂未匹配到诊断类型（请检查灯塔、白友两边系统诊疗号是否匹配）",
            });
          } else {
            this.$Message.success(`患者${row.user_name}同步成功`);
            this._arriveReport("getList");
          }
        });
      }, 300);
    },
    batchData() {
      this.batchLoading = true;
      const params = {
        start_time: dayjs(this.formItem.dateMonth[0]).format("YYYY-MM-DD"),
        end_time: dayjs(this.formItem.dateMonth[1]).format("YYYY-MM-DD"),
      };
      arrivereportSync(params)
        .then((res) => {
          if (res.matching_num == 0) {
            this.$Modal.error({
              title: "温馨提示",
              content:
                "当前存在部分数据(" +
                res.matching_diff +
                "条)未能匹配到，未能匹配到的数据，请检查灯塔、白友两边系统诊疗号是否匹配",
            });
          } else {
            this.$Message.success("同步成功");
            this._arriveReport("getList");
          }
          this._arriveReport("getList");
          this.batchLoading = false;
        })
        .catch(() => {
          this.batchLoading = false;
        });
    },
    consumeauthlist() {
      consumeauthlist().then((res) => {
        this.member = res;
        // console.log(res,'res')
        this._arriveReport("getList");
      });
    },
    changePage(value) {
      this.formItem.page = value;
      this._arriveReport("getList");
    },
    changeSize(value) {
      this.formItem.pageSize = value;
      this.formItem.page = 1;
      this._arriveReport("getList");
    },
    exportData() {
      this._arriveReport("export");
    },
    // 初始化下拉框的信息
    _patientReportInfo() {
      patientReportInfo().then((res) => {
        this.source_channel_list = res.source_channel_list;
        this.source_channel_market_list = res.source_channel_market_list;
        this.diseases_list = res.diseases_list;
        this.member_list = res.member_list;
        this.belongData = JSON.parse(JSON.stringify(res.member_list));
        this.channel_types = res.source_channel_list;
        // this.channel = res.channel;
      });
    },
    keyWordSearch(value) {
      this.formItem.page = 1;
      this._arriveReport("getList");
    },
    clearKeyWord(value) {
      this.formItem.page = 1;
      this._arriveReport("getList");
    },
    // 切换参数
    changeParams() {
      this.formItem.page = 1;
      this._arriveReport("getList");
    },
    _arriveReport(type) {
      let params = {
        // source_channel_type: this.formItem.keyword
        //   ? ""
        //   : this.formItem.source_channel_type !== "" &&
        //     this.formItem.source_channel_type !== undefined
        //   ? this.formItem.source_channel_type
        //   : "",
        // start_time: this.formItem.dateMonth[0].format('YYYY-MM-DD'),
        // end_time: this.formItem.dateMonth[1].format('YYYY-MM-DD'),
        start_time: dayjs(this.formItem.dateMonth[0]).format("YYYY-MM-DD"),
        end_time: dayjs(this.formItem.dateMonth[1]).format("YYYY-MM-DD"),
        // un_consume: this.formItem.keyword
        //   ? ""
        //   : this.formItem.noConsumer
        //   ? 1
        //   : "",
        un_by: this.formItem.keyword ? "" : this.formItem.un_by ? 1 : "",
        belong_member_id: this.formItem.keyword
          ? ""
          : this.belongValue && this.belongValue.join(",") !== undefined
          ? this.belongValue.join(",")
          : "",
        patient_diseases_id: this.formItem.keyword
          ? ""
          : this.formItem.diseases_id && this.formItem.diseases_id !== undefined
          ? this.formItem.diseases_id
          : "",
        channel_id: this.formItem.keyword
          ? ""
          : this.formItem.source_channel_id &&
            this.formItem.source_channel_id !== undefined
          ? this.formItem.source_channel_id
          : "",
        market_id: this.formItem.keyword
          ? ""
          : this.formItem.source_channel_id &&
            this.formItem.source_channel_id !== undefined
          ? this.formItem.source_channel_id
          : "",
        keyword: this.formItem.keyword,
        page: this.formItem.page,
        pageSize: this.formItem.pageSize,
      };
      switch (type) {
        case "getList":
          this.loading = true;
          // 添加列
          let condition = [];
          if (+this.section_id === 2) {
            condition = [
              {
                title: "消费",
                key: "first_consume",
                width: 100,
                render: (h, params) => {
                  return h(
                    "div",
                    {},
                    params.row.by_revisiting_time === "" &&
                      params.row.kq_reality_money === "0.00"
                      ? "/"
                      : params.row.kq_reality_money
                  );
                },
              },
              {
                title: "退费",
                key: "kq_refund",
                width: 100,
                render: (h, params) => {
                  return h(
                    "div",
                    {},
                    params.row.by_revisiting_time === "" &&
                      params.row.kq_refund === "0.00"
                      ? "/"
                      : params.row.kq_refund
                  );
                },
              },
            ];
          } else if (
            +this.info.is_super === 1 ||
            this.member.includes(+this.info.member_id)
          ) {
            condition = [
              // {
              //     title: '初诊消费',
              //     key: 'first_consume',
              //     width: 100,
              //     render: (h, params) => {
              //         return h(
              //             'div',
              //             {},
              //             params.row.by_revisiting_time === '' &&
              //             params.row.first_consume === '0.00'
              //                 ? '/'
              //                 : params.row.first_consume
              //         );
              //     }
              // },
              // {
              //     title: '季度消费',
              //     key: 'quarter_consume',
              //     width: 100,
              //     render: (h, params) => {
              //         return h(
              //             'div',
              //             {},
              //             params.row.by_revisiting_time === '' &&
              //             params.row.quarter_consume === '0.00'
              //                 ? '/'
              //                 : params.row.quarter_consume
              //         );
              //     }
              // },
              // {
              //     title: '年度消费',
              //     key: 'year_consume',
              //     width: 100,
              //     render: (h, params) => {
              //         return h(
              //             'div',
              //             {},
              //             params.row.by_revisiting_time === '' &&
              //             params.row.year_consume === '0.00'
              //                 ? '/'
              //                 : params.row.year_consume
              //         );
              //     }
              // }
            ];
          }
          let data = JSON.parse(JSON.stringify(this.columnss));
          if (condition.length > 0) {
            data.push(...condition);
          }
          this.columns = data;

          arriveReport(params).then((res) => {
            this.loading = false;
            this.dataWithPage = res.list;
            this.total = res.total;
          });
          break;
        case "export":
          delete params.page;
          delete params.pageSize;
          arriveReportExport(params).then((res) => {
            const link = document.createElement("a");
            let blob = new Blob([res], {
              type: "application/vnd.ms-excel",
            });
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            link.download = "到诊关联表.xls"; // 下载的文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          });
          break;
      }
    },
    changeParamsChannel(value) {
      if (value === 0) {
        this.channel_types = this.source_channel_list;
      } else if (value === 1) {
        this.channel_types = this.source_channel_market_list;
      } else {
        this.channel_types = [];
      }
      this.formItem.source_channel_id = "";
      this.changeParams();
    },

    valueChange(e) {
      this.belongValue = [];
      e.forEach((item) => {
        let flag = true;
        this.belongData.forEach((ele) => {
          if (ele.value == item) {
            flag = false;
            ele.children.forEach((id) => {
              this.belongValue.push(id.value);
            });
          }
        });
        if (flag) {
          this.belongValue.push(item);
        }
      });
      this._arriveReport("getList");
    },
  },
};
</script>
<style lang="less">
.vue-treeselect {
  display: inline-block;
  vertical-align: middle;
}
.vue-treeselect__control {
  height: 32px;
}
.vue-treeselect__control {
  min-width: 150px;
  width: auto;
}
</style>
